package javaweb.tail;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import javaweb.tail.util.DBUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/welcome"})
public class WelcomeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = null;
        String password = null;

        // 获取Cookie对象集
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("username")){
                    username = cookie.getValue();
                }else if(cookie.getName().equals("password")){
                    password = cookie.getValue();
                }
            }
        }
        // 如果存在判断用户名和密码是否正确，错误则直接返回到登录页面
        if(username!=null&&password!=null){
            Connection conn = null;
            PreparedStatement ps =null;
            ResultSet rs = null;
            boolean flag = false;
            try{
                conn = DBUtil.getConnection();
                String sql = "select * from user where password=? and username=?";
                ps = conn.prepareStatement(sql);
                ps.setString(1,password);
                ps.setString(2,username);
                rs = ps.executeQuery();
                if(rs.next()){
                    flag = true;
                }

            }catch (SQLException e){
                e.printStackTrace();
            }finally {
                DBUtil.close(conn,ps,rs);
            }
            if(flag){
                //这里登录成功也要建一下session会话对象
                //因为session对象浏览器关了就找不着了，而cookie是还在的
                HttpSession session = request.getSession();
                session.setAttribute("username",username);
                response.sendRedirect(request.getContextPath() + "/mytail.jsp");
            }else {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }else{
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }
}
